﻿using System;
using System.Windows.Forms;
using WorkFlowBLL;
using Library;
using System.Drawing;

namespace QLCF.Forms
{
    public partial class frmProduct : Form
    {
        public Boolean isAddData = false;

        private bool isLoading = true;        

        public int m_productID = -1;

        public int m_quantity = -1;

        public string m_productName = string.Empty;

        public string m_unit = string.Empty;

        public int m_categoryID = -1;
        public int m_categoryIDCurrent = -1;

        public int permission = 0;

        public frmProduct()
        {
            InitializeComponent();
            lstViewCate_LoadData();
            permission = CtrAdmin.GetPermission(Program.UserEntity.Permission, Config.Enum.Function.frmProduct);

            if ((permission & (int)Config.Enum.Permission.Add) != (int)Config.Enum.Permission.Add)
            {
                tsbAdd.Enabled = false;
                toolStripMenuItemAdd.Enabled = false;
            }

            if ((permission & (int)Config.Enum.Permission.Edit) != (int)Config.Enum.Permission.Edit)
            {
                tsbEdit.Enabled = false;
                toolStripMenuItemEdit.Enabled = false;
                toolStripMenuItemUpdateQuanlity.Enabled = false;
            }

            if ((permission & (int)Config.Enum.Permission.Delete) != (int)Config.Enum.Permission.Delete)
            {
                tsbDelete.Enabled = false;
                toolStripMenuItemDelete.Enabled = false;
            }
        }

        private void lstViewCate_LoadData()
        {
            TreeNode node1 = new TreeNode();
            node1.Text = "Tất cả";
            node1.Tag = -1;
            node1.ImageIndex = 1;
            node1.SelectedImageIndex = 1;
            treeViewCategory.Nodes.Add(node1);
            CtrCategory ctrC = new CtrCategory();
            var items = ctrC.GetListCategory(-1);
            foreach (var item in items)
            {
                TreeNode node = new TreeNode();
                node.Text = item.CategoryName;
                node.Tag = item.CategoryID;
                node.ImageIndex = 0;
                treeViewCategory.Nodes.Add(node);
            }            
        }        

        private void treeViewCategory_AfterSelect(object sender, TreeViewEventArgs e)
        {            
            var cateID = Convert.ToInt32(e.Node.Tag);
            this.bindData(cateID);
            this.m_categoryID = cateID;
            e.Node.BackColor = Color.FromArgb(220, 220, 220);
        }
        
        private void frmProduct_Load(object sender, EventArgs e)
        {
            splitContainer1.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;            
            splitContainer1.Location = new Point(0, 20);splitContainer1.Size = new Size(splitContainer1.Parent.ClientSize.Width, splitContainer1.Parent.ClientSize.Height - (0 + 20));
            this.isLoading = false;            
        }

        public void bindData(int m_cateID)
        {
            CtrProduct ctrT = new CtrProduct();
            var lstProduct = ctrT.ProductGetByCate(m_cateID, -1, -1);
            if (lstProduct.Count > 0)
            {
                grvProduct.AutoGenerateColumns = false;
                grvProduct.DataSource = lstProduct;
                this.isLoading = false;
                grvProduct.Select();
            }
            else
            {
                grvProduct.DataSource = null;
            }         
        }

        private void tsbAdd_Click(object sender, EventArgs e)
        {
            this.isAddData = true;
            frmProductDetail frmProductDetail = new frmProductDetail(this);
            clsControls.ClearTextBox(frmProductDetail);               
            frmProductDetail.ShowDialog();
            frmProductDetail.Dispose();
        }

        private void tsbEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.isLoading) return;
                this.isAddData = false;
                frmProductDetail frmProductDetail = new frmProductDetail(this);                
                frmProductDetail.ShowDialog();
                frmProductDetail.m_productID = this.m_productID;
            }
            catch (Exception loi)
            {
                MessageBox.Show(loi.Message.ToString());
            }
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Bạn chắc chắn xoá bản ghi này không?", "Thông báo...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
                CtrProduct ctrProduct = new CtrProduct();
                var objDelete = ctrProduct.ProductDelete(this.m_productID);
                if (objDelete > 0)
                {
                    CtrAdmin ctra = new CtrAdmin();
                    ctra.LogInsert(Program.UserEntity.UserID, Program.UserEntity.UserName, 3, "Xóa sản phẩm \"" + this.m_productName + "\" có mã \"" + this.m_productID + "\"", "Quản lý mặt hàng");

                    MessageBox.Show("Xóa sản phầm thành công!", "Thông báo...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.bindData(this.m_categoryID);
                    return;
                }
                else if (objDelete == -1 || objDelete == -2)
                {
                    MessageBox.Show("Sản phẩm đang được sử dụng trên hệ thống. Bạn không thể xóa sản phẩm này !", "Thông báo...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }                
                else
                {
                    MessageBox.Show("Lỗi xóa sản phẩm !", "Thông báo...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());                
            }                  
        }

        private void tsbPrint_Click(object sender, EventArgs e)
        {

        }

        private void tsbRefresh_Click(object sender, EventArgs e)
        {
            this.bindData(this.m_categoryID);
        }

        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void grvProduct_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {                
                SolidBrush b = new SolidBrush(grvProduct.RowHeadersDefaultCellStyle.ForeColor);
                e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), grvProduct.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
            }
            catch { }
        }        

        private void grvProduct_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.isLoading) return;
            var row = e.RowIndex;
            m_productID = Convert.ToInt32(grvProduct.Rows[row].Cells["ProductID"].Value);
            m_productName = grvProduct.Rows[row].Cells["ProductName"].Value.ToString();
            m_unit = grvProduct.Rows[row].Cells["UnitName"].Value.ToString();
            m_quantity = Convert.ToInt32(grvProduct.Rows[row].Cells["CurrentQuantity"].Value);
            m_categoryIDCurrent = Convert.ToInt32(grvProduct.Rows[row].Cells["CategoryID"].Value);
        }

        private void grvProduct_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            tsbEdit.PerformClick();
        }       

        private void grvProduct_MouseDown(object sender, MouseEventArgs e)
        {            
            if (e.Button == MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = grvProduct.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    grvProduct.ClearSelection();
                    grvProduct.CurrentCell = grvProduct.Rows[hti.RowIndex].Cells[hti.ColumnIndex];
                    grvProduct.Rows[hti.RowIndex].Cells[hti.ColumnIndex].Selected = true;                    
                    grvProduct.ContextMenuStrip = contextMenuStripOnProduct;                    
                    contextMenuStripOnProduct.Items["toolStripMenuItemEdit"].Enabled = true;
                    contextMenuStripOnProduct.Items["toolStripMenuItemRefresh"].Enabled = true;
                    contextMenuStripOnProduct.Items["toolStripMenuItemDelete"].Enabled = true;                    
                }
                else
                {
                    contextMenuStripOnProduct.Items["toolStripMenuItemEdit"].Enabled = false;
                    contextMenuStripOnProduct.Items["toolStripMenuItemRefresh"].Enabled = true;
                    contextMenuStripOnProduct.Items["toolStripMenuItemDelete"].Enabled = false;                    
                }
            }
        }

        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            tsbAdd.PerformClick();
        }

        private void toolStripMenuItemEdit_Click(object sender, EventArgs e)
        {
            tsbEdit.PerformClick();
        }

        private void toolStripMenuItemRefresh_Click(object sender, EventArgs e)
        {
            tsbRefresh.PerformClick();
        }

        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            tsbDelete.PerformClick();
        }

        private void treeViewCategory_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (treeViewCategory.SelectedNode != null)
                treeViewCategory.SelectedNode.BackColor = Color.Transparent;
        }

        private void toolStripMenuItemUpdateQuanlity_Click(object sender, EventArgs e)
        {
            popupProductSetQuantity popupProductSetQuantity = new popupProductSetQuantity(this, this.m_productID, this.m_productName, this.m_unit, this.m_quantity);            
            popupProductSetQuantity.ShowDialog();            
        }

        public void updateQuantity(int productID, double quantity)
        {
            CtrProduct ctrP = new CtrProduct();
            if (ctrP.ProductUpdateQuantity(productID, quantity) > 0)
            {
                CtrAdmin ctra = new CtrAdmin();
                ctra.LogInsert(Program.UserEntity.UserID, Program.UserEntity.UserName, 2, "Cập nhật sản phẩm \"" + this.m_productName + "\" với số lượng \"" + quantity + "\"" + this.m_unit + "\"", "Quản lý mặt hàng");
                this.bindData(this.m_categoryID);
            }
        }
    }
}
